package com.zt.ztyh.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zt.ztyh.dto.*;
import com.zt.ztyh.entity.Bankcards;
import com.zt.ztyh.entity.Ztyhuserbankcards;
import com.zt.ztyh.exception.ZhentaoException;
import com.zt.ztyh.service.BankcardsService;
import com.zt.ztyh.service.ZtyhuserbankcardsService;
import com.zt.ztyh.utils.IdWorker;

import com.zt.ztyh.vo.common.Result;
import com.zt.ztyh.vo.common.ResultCodeEnum;
import jakarta.annotation.Resource;
import org.apache.poi.ss.formula.functions.T;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Random;

/**
 * @author 王利明
 */
@RestController
@RequestMapping("/bankcards")
public class BankCardsController {
      IdWorker idWorker=new IdWorker();

      @Autowired
      private BankcardsService bankcardsService;
      @Autowired
      private ZtyhuserbankcardsService ztyhuserbankcardsService;
      /**
       *转账时判断 银行卡号是否存在
       *验证是否是一类卡
       *验证所属银行
       */
      @GetMapping("/cardsole")
      public Result cardsole(@RequestParam("cardnumber")String cardnumber){
            System.err.println(cardnumber);
            QueryWrapper<Bankcards> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("cardnumber",cardnumber);

            Bankcards one = bankcardsService.getOne(queryWrapper);
            if(one.getZid()!=null){
                  return Result.build(one,201,"该银行卡已绑定其他账户");
            }else{
                  return Result.build(one,200,"该银行卡可用");
            }
      }



      /**用户开户:查询该用户是否拥有一类卡  判断 一类卡是否存在
       * 参数：用户个人信息对象，包含姓名、身份证号、手机号、性别、银行卡密码
       * 卡号 hutool自动生成
       */

      @PostMapping("/opencard")
      @Transactional
      public Result openCard(@RequestBody Bankcards bankcards,
                             @RequestParam("uid")String uid){
            System.out.println(uid);
            Random random = new Random();
            long randomNumber = (long) (random.nextDouble() * Math.pow(10, 15)) + (long) Math.pow(10, 14);
            String sixteenDigitNumber = String.format("%016d", randomNumber);
            bankcards.setId(idWorker.nextId());
            bankcards.setCardnumber(sixteenDigitNumber);
            bankcards.setPaypassword("000000");
            bankcardsService.save(bankcards);
            Ztyhuserbankcards ztyhuserbankcards=new Ztyhuserbankcards();
            ztyhuserbankcards.setBid(bankcards.getId());
            ztyhuserbankcards.setUid(Long.valueOf(uid));
            ztyhuserbankcardsService.save(ztyhuserbankcards);
            return Result.build(bankcards, ResultCodeEnum.SUCCESS);
      }

      /**
       * 银行卡转账
       * 转入: 银行卡号  转入金额   持卡人
       * 转出:  银行卡号  转出金额   持卡人  银行卡密码   收款人姓名  收款人卡号
       * 转账记录:   转账时间   银行卡号  转出金额   持卡人  银行卡密码 收款人姓名  收款人卡号  联系方式
       */
      @PutMapping("/transfer")
      public Result transfer(@RequestBody ZhuanZhangDto zhuanZhangDto,
                             @RequestParam("cardnumber") String cardnumber){
            String phone = zhuanZhangDto.getPhone();
            String code = zhuanZhangDto.getCode();

            if (!redisTemplate.opsForValue().get(phone + "_" + code).equals(code)){
                  throw new ZhentaoException(ResultCodeEnum.CAPTCHA_ERROR);
            }
            QueryWrapper<Bankcards> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("cardNumber",cardnumber);
            Bankcards one = bankcardsService.getOne(queryWrapper);
            if (!one.getPaypassword().equals(zhuanZhangDto.getPaypassword())){
                  return Result.build(zhuanZhangDto.getPaypassword(), ResultCodeEnum.PASSWORD_ERROR);
            }
            if(one.getBalance().compareTo(zhuanZhangDto.getBalance())<0){
                  return Result.build(zhuanZhangDto.getBalance(), ResultCodeEnum.STOCK_LESS);
            }
            QueryWrapper<Bankcards> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("cardNumber",zhuanZhangDto.getCardnumber());
            Bankcards one1 = bankcardsService.getOne(queryWrapper1);
            one1.setBalance(one1.getBalance().add(zhuanZhangDto.getBalance()));
            bankcardsService.save(one1);
            return Result.build(null, ResultCodeEnum.SUCCESS);
      }

   @PostMapping("/bindings")
   public Result<T> bindings(@RequestParam("cardnumber") String cardnumber,
                             @RequestParam("id") Long id){
            QueryWrapper<Bankcards> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("cardNumber",cardnumber);
            Bankcards one = bankcardsService.getOne(queryWrapper);
           Ztyhuserbankcards ztyhuserbankcards=new Ztyhuserbankcards();
           ztyhuserbankcards.setUid(id);
           ztyhuserbankcards.setBid(one.getId());
           ztyhuserbankcardsService.save(ztyhuserbankcards);
           return Result.build(ztyhuserbankcards, ResultCodeEnum.SUCCESS);
      }

      /**
       * 充值到余额
       * @param balance
       * @param cardnumber
       * @return
       */


      @PutMapping("/account")
      public Result account(@RequestParam("balance")String balance,@RequestParam("cardnumber")String cardnumber){
            BigDecimal b=new BigDecimal(balance);
            QueryWrapper<Bankcards> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("cardNumber",cardnumber);
            Bankcards one = bankcardsService.getOne(queryWrapper);
            int i = one.getBalance().compareTo(b);
            if(i<0){
                  return Result.build(one.getBalance(), ResultCodeEnum.STOCK_LESS);
            }else{
                  one.setBalance((one.getBalance().subtract(b)));
            }
            bankcardsService.saveOrUpdate(one);
            return Result.build(one, ResultCodeEnum.SUCCESS);
      }

      /**
       * 提现到银行卡:  金额     判断账号余额
       * @param balance
       * @return
       */
      @PutMapping("/chong")
      public Result chong(@RequestParam("balance")String balance,@RequestParam("cardnumber")String cardnumber){
            BigDecimal b=new BigDecimal(balance);
            QueryWrapper<Bankcards> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("cardNumber",cardnumber);
            Bankcards one = bankcardsService.getOne(queryWrapper);
            one.setBalance(one.getBalance().add(b));
            bankcardsService.saveOrUpdate(one);
            return Result.build(one, ResultCodeEnum.SUCCESS);
      }

      /**
       * 判断银行卡密码是否正确
       */
      @GetMapping("/checkPass")
      public Result check(@RequestParam("cardnumber")String cardnumber,
                          @RequestParam("password")String password){
            QueryWrapper<Bankcards> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("cardNumber",cardnumber);
            queryWrapper.eq("payPassword",password);
            Bankcards one = bankcardsService.getOne(queryWrapper);
            if(one!=null){
                  return Result.build(one, 200,"密码正确");
              }else{
                  return Result.build(one, 201,"密码错误");
            }
          }

      /**
       *修改密码：银行卡卡号 原密码   持卡人姓名 手机号     新密码    短信验证码？
       * 根据 银行卡卡号 原密码   持卡人姓名 手机号 查询  如果匹配正确 进行修改密码
       */
      @Autowired
      private RedisTemplate<String,String> redisTemplate;
      @PutMapping("/change")
      public Result change(@NotNull @RequestBody BankcardsDto bankcardsDto){

            String phone = bankcardsDto.getPhone();
            String code = bankcardsDto.getCode();

            if (!redisTemplate.opsForValue().get(phone + "_" + code).equals(code)){
                  throw new ZhentaoException(ResultCodeEnum.CAPTCHA_ERROR);
            }            QueryWrapper<Bankcards> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("payPassword", bankcardsDto.getPaypassword());
            queryWrapper.eq("cardNumber", bankcardsDto.getCardnumber());
            Bankcards one = bankcardsService.getOne(queryWrapper);
            if (one != null) {
                  one.setPaypassword(bankcardsDto.getNewPaypassword());
                  bankcardsService.saveOrUpdate(one);
                  return Result.build(one, ResultCodeEnum.SUCCESS);
            }
            return Result.build(null, ResultCodeEnum.DATA_ERROR);
      }
      /**
       *注销或挂失 卡号  密码   银行卡预留手机号   短信验证码？
       *持卡人
       */
      @PutMapping("/cancel")
      public Result cancel(@RequestBody ChangeDto changeDto){
            String phone = changeDto.getPhone();
            String code = changeDto.getCode();

            if (!redisTemplate.opsForValue().get(phone + "_" + code).equals(code)){
                  throw new ZhentaoException(ResultCodeEnum.CAPTCHA_ERROR);
            }
            QueryWrapper<Bankcards> wrapper = new QueryWrapper<>();
            wrapper.eq("cardNumber",changeDto.getCardnumber());
            wrapper.eq("payPassword",changeDto.getPaypassword());
            Bankcards one = bankcardsService.getOne(wrapper);
            if(changeDto.getStatus()==1){
                 one.setStatus(0);
                 bankcardsService.saveOrUpdate(one);
                 return Result.build(one, ResultCodeEnum.SUCCESS);
           }
            if(changeDto.getStatus()==2){
                   one.setStatus(1);
                   bankcardsService.saveOrUpdate(one);
                  return Result.build(one, ResultCodeEnum.SUCCESS);
           }
            return Result.build(null, ResultCodeEnum.SUCCESS);
      }

      /**
       * 余额查询  卡号   密码
       */
      @GetMapping("/balance")
      public Result balance(@RequestParam("cardnumber") String cardnumber){
            QueryWrapper<Bankcards> wrapper = new QueryWrapper<>();
            wrapper.eq("cardNumber",cardnumber);
            Bankcards one = bankcardsService.getOne(wrapper);
            return Result.build(one.getBalance(), ResultCodeEnum.SUCCESS);
      }

      /**
       * 绑定账户 手机号 银行卡
       * 填写银行卡开卡时的手机号（注意：银行卡预留手机号与开户手机号不一致则不能绑定）
       * 验证密码是否正确
       * 通过给手机发送验证码到手机号，60s后需要手动重新发送
       */
      @PostMapping("/bind")
      public Result bind(@RequestBody BIndDto bIndDto,@RequestParam("cardnumber") String cardnumber){
            QueryWrapper<Bankcards> wrapper=new QueryWrapper<>();
            wrapper.eq("cardnumber",bIndDto.getCardnumber());
            wrapper.eq("level",1);
            Bankcards one = bankcardsService.getOne(wrapper);
            if(!one.getRealname().equals(bIndDto.getRealname())){
                  return Result.build(null,201,"持卡人错误");
            }
            if (!one.getPhone().equals(bIndDto.getPhone())){
                  return Result.build(null,202,"银行卡预留手机号错误");
            }
            String phone = bIndDto.getPhone();
            String code = bIndDto.getCode();

            if (!redisTemplate.opsForValue().get(phone + "_" + code).equals(code)){
                  throw new ZhentaoException(ResultCodeEnum.CAPTCHA_ERROR);
            }
                  QueryWrapper<Bankcards> wrapper1=new QueryWrapper<>();
                  wrapper1.eq("cardnumber",cardnumber);
                  Bankcards one1 = bankcardsService.getOne(wrapper1);
                   one1.setZid(one.getId());
                   bankcardsService.saveOrUpdate(one1);
                  return Result.build(null,200,"true");
      }

      /**
       * 登录成功 之后   查询名下所有本行银行卡信息
       */
      @GetMapping("/list")
      public Result list(@RequestParam("phone")String phone){
            return Result.build(bankcardsService.findAll(phone), ResultCodeEnum.SUCCESS);
      }

}
